import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store/index.js'
// 路由组件
import Login from '@/views/Login/Login'
import Main from '@/views/Main/Main'
import Home from '@/views/Home/Home'
import User from '@/views/User/User'
import Search from '@/views/Search//Search'
import SearchResult from '@/views/SearchResult/SearchResult.vue'
import ArticleDetail from '@/views/ArticleDetail/ArticleDetail.vue'
import UserEdit from '@/views/User/UserEdit.vue'
import Chat from '@/views/Chat/Chat.vue'

// 1. 将 VueRouter 本身提供的 $router.push 方法转存到常量中
const originalPush = VueRouter.prototype.push
// 2. 自定义 $router.push 方法，在内部调用原生的 originalPush 方法进行路由跳转；并通过 .catch 捕获错误
VueRouter.prototype.push = function push (location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  // 通过 .catch 捕获错误
  return originalPush.call(this, location).catch(err => err)
}

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    component: Main,
    children: [
      // path 为"空字符串"的子路由规则，叫做"默认子路由"
      {
        path: '',
        component: Home,
        name: 'home',
        meta: { keepAlive: true, top: 0 }
      },
      {
        path: '/user',
        component: User,
        name: 'user'
      }
    ]
  },
  {
    path: '/login',
    component: Login,
    name: 'login'
  },
  {
    path: '/search',
    component: Search,
    name: 'search'
  },
  {
    path: '/search/:kw',
    component: SearchResult,
    name: 'search-results',
    props: true
  },
  {
    path: '/article/:id',
    component: ArticleDetail,
    name: 'art-detail',
    props: true
  },
  {
    path: '/user/edit',
    component: UserEdit,
    name: 'user-edit'
  },
  {
    path: '/chat',
    component: Chat,
    name: 'chat'
  }

]

const router = new VueRouter({
  routes
})

// 所有有权限页面的路径，都在这个数组之中
const pagePathArr = ['/user', '/user/edit']

// 为路由的实例对象挂载全局前置守卫
router.beforeEach((to, from, next) => {
  // 如果将要离开的路由对象的 meta 元信息中，keepAlive 的值为 true
  if (from.meta.keepAlive) {
    // 则动态为元信息的 top 属性赋值（值是当前滚动条在纵向上滚动的位置）
    from.meta.top = window.scrollY
  }

  // 访问有权限的页面
  if (pagePathArr.indexOf(to.path) !== -1) {
    // 1. 从 store 中获取 token 的值
    //    注意：store.state.tokenInfo 要么是 {} 空对象，要么是包含 {token, refresh_token} 的对象
    const tokenStr = store.state.tokenInfo.token

    if (tokenStr) {
      // token 有值直接放行
      next()
    } else {
      // 没有 token 强制跳转到登录页面
      next(`/login?pre=${to.fullPath}`)
    }
  } else {
    // 访问没权限的页面
    next()
  }
})

export default router
